import os.path
import re

from docx import Document
from docx_parse import re_parse, redefine_with_level, check_catalog_to_df

# 依次并排父子标题
def split_title(result):
    chap_lv = [len(i.split('.')) for i in result['章节索引']]
    join_titles = redefine_with_level(result['标题'], chap_lv)
    for lv_i in range(max(chap_lv)):
        result[f'{lv_i + 1}'] = [''] * len(join_titles)
    for i, join_title in enumerate(join_titles):
        titles = join_title.split("___")
        for j, sub_t in enumerate(titles):
            result[f'{j + 1}'][i] = sub_t
    return result


"""
正则匹配获得表'<table:([^>]+)>'
正则匹配获得图'<image:([^>]+)>'
"""
path = './data/5S管理规定.docx'
name = os.path.basename(path).split('.')[0:-1][0]

csv_path = './out/csv文件'
img_path = './out/图片'
doc = Document(path)
pattern = re.compile('[\\t\\n\\r][1-9]+(?:\.\d{0,3})*')  # 正则匹配1，1.1，1.1.1，1.1.1.1等样式
result = re_parse(name, doc, pattern, img_path)
dataframe = check_catalog_to_df(split_title(result))
if not os.path.exists(csv_path):
    os.makedirs(csv_path)
dataframe.to_excel(f'./out/csv文件/{name}.xlsx', index=False)
